package com.diors.game.engine.network;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;

import com.diors.commons.network.module.ModuleManager;
import com.diors.commons.network.module.Resolve;
import com.diors.commons.network.module.model.MethodModel;
import com.diors.commons.thread.task.SelecterAction;


/**
 * 游戏连接数据包
 * @author	darren.ouyang <ouyang.darren@gmail.com>
 * @date	2013-10-21
 * @version 1.0
 * @copyright Copyright (c) 2013, darren.ouyang
 */
public class GameClientPacket extends SelecterAction
{
	
	static Logger log = Logger.getLogger(GameClientPacket.class);
	
	MethodModel methodModel;
	GameClient conn;
	ChannelBuffer buff;
	
	private Object[] objs;
	
	GameClientPacket(GameClient conn, ChannelBuffer buff) 
	{
		this.conn = conn;
		this.buff = buff;
	}

	boolean processData() throws Exception
	{
		int key = buff.readShort();
		int opcode = buff.readShort();
		
		MethodModel model = ModuleManager.getReceivable(key, opcode);
		if (model == null)
			return false;
		
		this.methodModel = model;
		
		/* 读取网络包 */
		objs = new Object[methodModel.getCommandInfoModel().length + 1];
		objs[0] = conn;
		Resolve.resolveReceivable(objs, buff, methodModel.getCommandInfoModel());
		return true;
	}

	@Override
	protected void execute() 
	{
		try 
		{			
			methodModel.execute(methodModel.getObj(), objs);
		} 
		catch (Throwable e) 
		{
			log.error(new StringBuilder().append(conn).append(",控制器:").
					append(methodModel.getObj().getClass().getName()).append("方法：").
					append(methodModel.getMethod().getName()).append("执行出错。").toString(), e);
		}
	}

	@Override
	public int selecterCode() 
	{
		return conn.getCommID();
	}

}
